package fem3d;

import java.io.IOException;

import inf.text.ArrayFormat;
import fem2.Constraint;
import fem2.Debugger;
import fem2.Edge;
import fem2.Force;
import fem2.MaterialModel;
import fem2.Mesh;
import fem2.Model;
import fem2.Node;
import fem2.analysis.Analysis;
import fem2.analysis.LinearStaticAnalysis;
import fem2.element.StructuralElement;
import fem2.element.TrussElement;
import fem2.enu.EchoLevelType;
import fem2.enu.SolverType;
import fem2.enu.State;
import fem2.material.StVenantKirchhoffMM;
import fem2.pre_and_post.GidPostStructural;

/**
 * desmonstrate truss element capability
 * 
 * @author hbui
 * 
 */
public class Frame {
	static String projDir = "/home/hbui/kratos_janosch";
	static String projName = "frame.gid";

	public Model createModel() {

		Mesh mesh = new Mesh();

		double l = 1000.0;
		double h = 1000.0;

		Node n1 = mesh.addNode(new Node(0.0, 0.0));
		Node n2 = mesh.addNode(new Node(l, 0.0));
		Node n3 = mesh.addNode(new Node(2 * l, 0.0));
		Node n4 = mesh.addNode(new Node(l, h));
		Node n5 = mesh.addNode(new Node(0.0, h));

		mesh.addEdge(new Edge(n1, n2));
		mesh.addEdge(new Edge(n2, n3));
		mesh.addEdge(new Edge(n3, n4));
		mesh.addEdge(new Edge(n2, n4));
		mesh.addEdge(new Edge(n1, n4));
		mesh.addEdge(new Edge(n4, n5));
		mesh.addEdge(new Edge(n1, n5));

		Constraint c1 = new Constraint(false, false);
		Constraint c2 = new Constraint(false, true);
		n1.setConstraint(c1);
		n5.setConstraint(c2);

		mesh.setNumberOfFields(2);

		Model m = new Model(mesh);

		double E = 206850; // =30*10^6 psi x 6.895*10^3 N/m^2
		double nu = 0.3;
		double t = 100;
		double rho = 7800.0e-9; // =7800 kg/m^3
		State ss = State.ONE_DIMENSIONAL;
		MaterialModel mm = new StVenantKirchhoffMM(E, nu, t, rho, ss);

		for (int i = 0; i < mesh.countEdges(); i++) {
			StructuralElement e = new TrussElement(mesh.getEdge(i), mm);
			m.addElement(e);
		}

		Force F = new Force(n3, 0, -1000);
		m.addLoad(F);

		return m;
	}

	public static void main(String[] args) throws IOException {
		Model m = new Frame().createModel();

		/*
		 * analysis
		 */
		Analysis an = new LinearStaticAnalysis(m);
		// ((NewtonRaphsonBasedStrategy) an.getStrategy())
		// .setMaxNewtonRaphsonIteration(1);
		an.getStrategy().setSolverType(SolverType.BAITSCH_SOLVER_GENERIC);
		an.getStrategy().setEchoLevel(EchoLevelType.OUTPUT, EchoLevelType.DEBUG);
		an.run();

		/*
		 * post process
		 */
		Mesh mesh = m.getMesh();
		for (int i = 0; i < mesh.countNodes(); i++) {
			System.out.println(ArrayFormat.format(mesh.getNode(i).getUHatLocal()));
		}

		GidPostStructural post = new GidPostStructural(projDir, projName);
		post.clearAllPostFiles();
		post.writeMesh(m, 0);
		post.writeNodalDisplacementResults(m, 0);

		Debugger.warn("Analysis completed");
	}
}
